import React, { useEffect, useRef } from 'react';
import * as monaco from 'monaco-editor';
import styles from './styles.module.css';

interface MonacoEditorProps {
  value?: string;
  language?: string;
  theme?: string;
  onChange?: (value: string | undefined) => void;
  readOnly?: boolean;
  height?: string | number;
}

const MonacoEditor: React.FC<MonacoEditorProps> = ({
  value = '',
  language = 'javascript',
  theme = 'vs-dark',
  onChange,
  readOnly = false,
  height = '300px',
}) => {
  const editorRef = useRef<monaco.editor.IStandaloneCodeEditor | null>(null);
  const containerRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    if (containerRef.current) {
      // 创建编辑器实例
      editorRef.current = monaco.editor.create(containerRef.current, {
        value,
        language,
        theme,
        readOnly,
        automaticLayout: true,
        minimap: {
          enabled: false,
        },
        scrollBeyondLastLine: false,
        fontSize: 14,
        lineNumbers: 'on',
        renderLineHighlight: 'all',
        scrollbar: {
          vertical: 'visible',
          horizontal: 'visible',
        },
      });

      // 监听内容变化
      editorRef.current.onDidChangeModelContent(() => {
        const newValue = editorRef.current?.getValue();
        onChange?.(newValue);
      });
    }

    // 清理函数
    return () => {
      if (editorRef.current) {
        editorRef.current.dispose();
      }
    };
  }, []);

  // 当 value 从外部更新时，更新编辑器内容
  useEffect(() => {
    if (editorRef.current && value !== editorRef.current.getValue()) {
      editorRef.current.setValue(value);
    }
  }, [value]);

  // 当语言改变时，更新编辑器语言
  useEffect(() => {
    if (editorRef.current) {
      monaco.editor.setModelLanguage(editorRef.current.getModel()!, language);
    }
  }, [language]);

  // 当主题改变时，更新编辑器主题
  useEffect(() => {
    if (editorRef.current) {
      monaco.editor.setTheme(theme);
    }
  }, [theme]);

  return (
    <div 
      ref={containerRef} 
      className={styles.editorContainer}
      style={{ height }}
    />
  );
};

export default MonacoEditor; 